package com.witmore.skyline.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.witmore.skyline.db.entity.DeviceDO;
import com.witmore.skyline.db.mapper.DeviceMapper;
import com.witmore.skyline.db.mapper.ProjectMapper;
import com.witmore.skyline.web.config.BusinessConfig;
import com.witmore.skyline.web.config.GlobalAccountSession;
import com.witmore.skyline.web.controller.vo.param.DeviceAttendanceParam;
import com.witmore.skyline.web.controller.vo.result.DeviceAttendanceVO;
import com.witmore.skyline.web.controller.vo.result.ResponseResult;
import com.witmore.skyline.web.service.DashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 大屏服务实现类
 * Author: 豆子高
 * Date: 2025/10/21
 */
@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private BusinessConfig businessConfig;

    @Override
    public ResponseResult<DeviceAttendanceVO> getDeviceAttendance(DeviceAttendanceParam param) {
        DeviceAttendanceVO vo = new DeviceAttendanceVO();

        // 构建基础查询条件
        LambdaQueryWrapper<DeviceDO> baseWrapper = new LambdaQueryWrapper<DeviceDO>()
                .eq(DeviceDO::getOrgId, GlobalAccountSession.getUserInfo().getOrgId())
                .eq(DeviceDO::getIsDeleted, 0)
                .eq(StringUtils.hasText(param.getProvince()), DeviceDO::getProvince, param.getProvince())
                .eq(StringUtils.hasText(param.getCity()), DeviceDO::getCity, param.getCity());

        // 1. 查询总设备数量
        Long totalDeviceCount = deviceMapper.selectCount(baseWrapper);
        vo.setDeviceTotal(totalDeviceCount.intValue());

        // 2. 实时设备出勤情况 - 施工设备数量（负荷）
        LambdaQueryWrapper<DeviceDO> loadWrapper = baseWrapper.clone()
                .in(DeviceDO::getWorkStatus, 2);
        Long todayWorkingDeviceCount = deviceMapper.selectCount(loadWrapper);
        vo.setDeviceLoadTotal(todayWorkingDeviceCount.intValue());

        // 3. 实时设备出勤情况 - 怠速设备数量（怠速&在线）
        LambdaQueryWrapper<DeviceDO> idleWrapper = baseWrapper.clone()
                .in(DeviceDO::getWorkStatus, 0, 1);
        Long idleDeviceCount = deviceMapper.selectCount(idleWrapper);
        vo.setDeviceIdlTotal(idleDeviceCount.intValue());

        // 4. 实时设备出勤情况 - 离线设备数量（离线）
        LambdaQueryWrapper<DeviceDO> offlineWrapper = baseWrapper.clone()
                .eq(DeviceDO::getWorkStatus, -1);
        Long offlineDeviceCount = deviceMapper.selectCount(offlineWrapper);
        vo.setDeviceOfflineTotal(offlineDeviceCount.intValue());

        // 5. 大屏地图顶部统计 - 今日施工设备数量（负荷大于=配置阈值）
        LambdaQueryWrapper<DeviceDO> loadWorkingWrapper = baseWrapper.clone()
                .and(wrapper -> wrapper.isNull(DeviceDO::getLoadWorkTime).or().ge(DeviceDO::getLoadWorkTime, businessConfig.getLoadWorkTimeThreshold()));
        Long deviceLoadWorkingTotal = deviceMapper.selectCount(loadWorkingWrapper);
        vo.setDeviceLoadWorkingTotal(deviceLoadWorkingTotal.intValue());

        // 5. 大屏地图顶部统计 - 今日未施工设备数量（负荷小于配置阈值）
        LambdaQueryWrapper<DeviceDO> notWorkingWrapper = baseWrapper.clone()
                .and(wrapper -> wrapper.isNull(DeviceDO::getLoadWorkTime).or().lt(DeviceDO::getLoadWorkTime, businessConfig.getLoadWorkTimeThreshold()));
        Long todayNotWorkingDeviceCount = deviceMapper.selectCount(notWorkingWrapper);
        vo.setDeviceUnWorkingTotal(todayNotWorkingDeviceCount.intValue());

        // 6. 大屏地图顶部统计 - 今日施工的项目部数量（负荷小于配置阈值）
        int todayWorkingProjectCount = deviceMapper.selectWorkingProjectCount(GlobalAccountSession.getUserInfo().getOrgId(), null, param.getProvince(), param.getCity(), businessConfig.getLoadWorkTimeThreshold());
        vo.setProjectWorkingTotal(todayWorkingProjectCount);

        // 7. 计算百分比（整数，四舍五入）
        if (totalDeviceCount > 0) {
            // 实时设备出勤情况 - 施工设备百分比（施工设备数量/总设备数量）
            BigDecimal todayWorkingPercentage = BigDecimal.valueOf(todayWorkingDeviceCount)
                    .divide(BigDecimal.valueOf(totalDeviceCount), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(0, RoundingMode.HALF_UP);
            vo.setDeviceLoadPercentage(todayWorkingPercentage);

            // 实时设备出勤情况 - 怠速设备百分比（怠速设备数量/总设备数量）
            BigDecimal idlePercentage = BigDecimal.valueOf(idleDeviceCount)
                    .divide(BigDecimal.valueOf(totalDeviceCount), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(0, RoundingMode.HALF_UP);
            vo.setDeviceIdlPercentage(idlePercentage);

            // 实时设备出勤情况 - 离线设备百分比（离线设备数量/总设备数量）
            BigDecimal offlinePercentage = BigDecimal.valueOf(offlineDeviceCount)
                    .divide(BigDecimal.valueOf(totalDeviceCount), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(0, RoundingMode.HALF_UP);
            vo.setDeviceOfflinePercentage(offlinePercentage);
        } else {
            vo.setDeviceLoadPercentage(BigDecimal.ZERO);
            vo.setDeviceIdlPercentage(BigDecimal.ZERO);
            vo.setDeviceOfflinePercentage(BigDecimal.ZERO);
        }

        return ResponseResult.success(vo);
    }
}
